package Version4;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class BootStrap {

    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void startUp() throws Exception {

        loadServlet();

        //创建一个服务器Socket对象
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );


        while (true) {

            //接收一个请求后
            Socket socket = serverSocket.accept();
            System.out.println("接收一个请求后");

            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);

        }
    }

    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    private void loadServlet() throws Exception {
        //获取资源文件的通用做法就是，使用 classLoader对象进行处理
        //关键就在于这个classLoader
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        //通过流构建一个对象出来，把流对象转换成了Document对象了
        Document document = saxReader.read(resourceAsStream);

        //第一步：获取一个根对象 在xml文件中 这里就是<web-app>
        Element rootElement = document.getRootElement();

        //获取servlet对象
        List<Element> selectNodes = rootElement.selectNodes("//servlet");

        for (int i = 0; i < selectNodes.size(); i++) {
            Element element = selectNodes.get(i);

            //<servlet>
            //<servlet-name>lagou</servlet-name>
            //<servlet-class>server.LagouServlet</servlet-class>
            //</servlet>

            //得到了servletName和class，现在需要对应映射url
            String servletName = element.selectSingleNode("servlet-name").getStringValue();
            String servletClass = element.selectSingleNode("servlet-class").getStringValue();


            //<servlet-mapping>
            //<servlet-name>lagou</servlet-name>
            //<url-pattern>/lagou</url-pattern>
            //</servlet-mapping>
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping['" + servletName + "']");

            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

            servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
        }
    }

    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();

        try {
            bootStrap.startUp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
